<template>
	<view>
		<view>
			<view class="bt-nav" bindtap="goIndex">
				蓝牙
			</view>
		 <view>
				<button @click="searchBlue()" type="primary">搜索蓝牙</button>
			</view>
			<view class="bt-news">
				<view class="list-item" v-if="!isHideList">
					<view class="item-box" v-for="(item,index) in devicesList" wx:key="index">
						<text class="bt-name">设备名称: {{item.name}}</text>
							<view class="btn-connection" :data-id="item.deviceId"
							:data-name="item.name" bindtap="connectTo">
							连接
						</view>
					</view>
				</view>
			</view>
			<!-- 连接成功 -->
			<view class="connect-success" v-if="!isHideConnect">
				<view class="show-news">
					<text>已连接到：{{connectName}}</text>
		 		<!-- <text>{{deviceId}}</text> -->
				</view>
				<view class="write-data">
					<button class="write-btn" size="mini" bindtap="writeBLECharacteristicValue">写入数据</button>
				</view>
				<view class="closeBLEConnection-box">
					<button class="closeBLEConnection" size="mini" bindtap="closeBLEConnection">断开连接</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "BlueTooth",
		created() {
			this.checkGpsModule();
		},
		methods: {
			//写入数据（发送请求）
			writeBLECharacteristicValue() { //页面有个按钮
				// 向蓝牙设备发送的16进制数据
				let that = this;
				let buffer = new ArrayBuffer(8);
				let dataView = new DataView(buffer);
				console.log(dataView); //第一个参数是字节序号，表示从哪个字节开始写入，第二个参数为写入的数据。
				let arr = that.data.queryData.query;
				arr.forEach((item, i) => {
					dataView.setInt8(i, arr[i]);
				})
				console.log(buffer)
				uni.writeBLECharacteristicValue({
					deviceId: that.data.writeNews.deviceId,
					serviceId: that.data.writeNews.serviceId,
					characteristicId: that.data.writeNews.characteristicId,
					value: buffer,
					success: (res) => {
						console.log(res);
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},

			//监听特征值变化（接收数据）
			notifyBLECharacteristicValueChange(serviceId, characteristicId) {
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: that.data.deviceId,
					serviceId,
					characteristicId,
					success(res) {
						console.log('notifyBLECharacteristicValueChange success');
						console.log(res);
						uni.onBLECharacteristicValueChange(function(res) {
							console.log(res);
							let str = that.ab2hex(res.value); //转为16进制字符串
							//这就是需要的字符了
						})
					}
				})
			},
			// ArrayBuffer转16进制字符串
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('');
			},
			//获取服务特征值
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				console.log(deviceId, 'serviceId=' + serviceId)
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						console.log(res);
						let characteristicId = res.characteristics[0].uuid; //要写数据的特征id
						let notifyId = res.characteristics[3].uuid; //监听特征变化的特征id（接收数据）
						that.notifyBLECharacteristicValueChange(serviceId, notifyId);
						let writeNews = {
							deviceId,
							serviceId,
							characteristicId
						};
						that.setData({
							writeNews: writeNews
						}); //写的时候需要用到
					},
					fail(err) {
						console.log('获取特征值失败:');
						console.log(err)
					},
				});

			},
			//获取服务以及服务的uuid                                             
			getBLEDeviceServices(deviceId) {
				let that = this;
				let serviceId;
				uni.getBLEDeviceServices({ //获取蓝牙设备所有服务
					deviceId,
					success: (res) => { //services：设备服务列表 uuid：服务id
						console.log(res);
						serviceId = res.services[1].uuid;
						that.getBLEDeviceCharacteristics(deviceId, serviceId); //去获取特征值
					},
				})
			},
			//连接蓝牙设备
			connectTo(e) {
				let that = this;
				let deviceId = e.currentTarget.dataset.id; //设备id
				let connectName = e.currentTarget.dataset.name; //连接的设备名称
				uni.showLoading({
					title: '连接中...',
				});
				uni.createBLEConnection({
					deviceId, // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					success(res) {
						uni.hideLoading();
						that.stopBluetoothDevicesDiscovery(); //停止搜索蓝牙
						console.log(res);
						if (res.errCode == 0) {
							console.log('连接成功');
							that.setData({
								deviceId: deviceId,
								connectName: connectName,
								isHideConnect: false, //显示已连接的蓝牙
							})
							that.getBLEDeviceServices(deviceId); //获取已连接蓝牙的服务
						} else if (res.errCode == 10012) {
							uni.showToast({
								title: '连接超时，请重试！',
							})
						}
					},
					fail(error) {
						uni.hideLoading();
						uni.showToast({
							title: error,
						})
					}
				});
			},
			//关闭搜索蓝牙
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log(res)
					}
				})
			},
			//搜索蓝牙设备
			searchBlue() {
				let that = this;
				wx.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					success(res) {
						wx.showLoading({
							title: '正在搜索设备',
						});
						wx.getBluetoothDevices({
							success: function(res) {
								console.log(res);
								let devicesListArr = [];
								if (res.devices.length > 0) { //如果有蓝牙设备就把蓝牙信息放到渲染列表里面
									wx.hideLoading();
									console.log(res.devices)
									res.devices.forEach(device => {
										if (!device.name && !device.localName) {
											return
										} else {
											uni.createBLEConnection({
												deviceId:device.deviceId,
											});
											uni.closeBLEConnection({
												deviceId:device.deviceId,
											});
											devicesListArr.push(device); //渲染数组
										}
									})
									that.devicesList = devicesListArr;
									console.log(devicesListArr)
									that.isHideList = false;
								} else {
									wx.hideLoading();
									wx.showModal({
										title: '温馨提示',
										content: '无法搜索到蓝牙设备，请打开GPS重新尝试',
										showCancel: false
									});
									wx.closeBluetoothAdapter({
										success(res) {
											console.log(res)
										}
									})
								}
							}
						})
					},
					fail: function(res) {
						wx.showToast({
							title: '搜索蓝牙外围设备失败,请重新初始化蓝牙!',
							icon: 'none',
						})
					}
				})
			},

			//初始化蓝牙模块
			openBluetoothAdapter() {
				let that = this;
				wx.openBluetoothAdapter({
					success(res) {
						console.log(res)
						that.isOpen = true;
						uni.onBluetoothAdapterStateChange((res) => {
							console.log(res)
							if (!res.available) { //蓝牙适配器是否可用
								uni.showModal({
									title: '温馨提示',
									content: '蓝牙蓝牙适配器不可用，请重新启动',
									showCancel: false
								})
							}
						})
						that.searchBlue(); //开始搜索蓝牙
					},
					fail(res) {
						console.log(res)
						if (res.errMsg == 'openBluetoothAdapter:fail auth deny') {
							uni.showModal({
								title: '提示',
								content: '请先授权蓝牙功能',
								success: (res) => {
									if (res.confirm) {
										that.openSetting()
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							})
						} else {
							uni.showToast({
								title: '请检查手机蓝牙是否打开',
								icon: 'none',
								duration: 2500
							})
						}
					},
				})
			},
			//打开设置面板
			openSetting() {
				let that = this;
				wx.openSetting({
					success(res) {
						if (res.authSetting['scope.bluetooth']) {
							that.searchBlue(); //开始搜索蓝牙
						}
					},
					fail: err => {
						console.log(err)
					}
				})
			},
			//安卓手机需要GPS才能搜索到蓝牙设备，所以需要提醒用户开启GPS
			checkGpsModule() {
				let that = this;
				uni.getSystemInfo({
					success(res) {
						let gps = res.locationEnabled;
						if (!gps) {
							uni.showModal({
								title: '请打开GPS定位',
								content: '不打开GPS定位，可能无法搜索到蓝牙设备',
								showCancel: false,
							})
						} else {
							that.openBluetoothAdapter(); //初始化蓝牙模块
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
</style>
